package com.srlg.controller;

import com.srlg.model.entity.UserInfo;
import io.quarkus.panache.common.Sort;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @desc:
 * @author: srlg li
 * @date: 2024/12/30 上午12:14
 */
@Path("userInfo")
@ApplicationScoped
@Produces("application/json")
@Consumes("application/json")
@Slf4j
public class UserInfoController {
    @GET
    public List<UserInfo> get() {
        return UserInfo.listAll(Sort.by("username"));
    }

    @GET
    @Path("{id}")
    public UserInfo getSingle(Long id) {
        UserInfo entity = UserInfo.findById(id);
        if (entity == null) {
            throw new WebApplicationException("info with id of " + id + " does not exist.", 404);
        }
        return entity;
    }

    @POST
    @Transactional
    public Response create(UserInfo info) {
        if (info.id != null) {
            throw new WebApplicationException("Id was invalidly set on request.", 422);
        }

        info.persist();
        return Response.ok(info).status(201).build();
    }

    @PUT
    @Path("{id}")
    @Transactional
    public UserInfo update(Long id, UserInfo info) {
        if (info.getUsername() == null) {
            throw new WebApplicationException("info Name was not set on request.", 422);
        }

        UserInfo entity = UserInfo.findById(id);

        if (entity == null) {
            throw new WebApplicationException("info with id of " + id + " does not exist.", 404);
        }

        entity.setUsername(info.getUsername());

        return entity;
    }

    @DELETE
    @Path("{id}")
    @Transactional
    public Response delete(Long id) {
        UserInfo entity = UserInfo.findById(id);
        if (entity == null) {
            throw new WebApplicationException("info with id of " + id + " does not exist.", 404);
        }
        entity.delete();
        return Response.status(204).build();
    }
}
